package com.zwk.nginxmanage.controller;

import com.zwk.nginxmanage.common.R;
import com.zwk.nginxmanage.config.ResourceConfig;
import com.zwk.nginxmanage.entity.NginxResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartResolver;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/view")
public class ViewController {

    private String pathPrefix;
    private String urlPrefix;
    private List<NginxResource> resourceList;
    @Autowired private ResourceConfig resourceConfig;


    @PostConstruct
    public void init(){
        this.pathPrefix=resourceConfig.getPathPrefix();
        this.urlPrefix=resourceConfig.getUrlPrefix();
        this.resourceList=resourceConfig.getResourceList();
    }

    /**
     * 获取目录名
     * @return
     */
    @GetMapping("/geCatelog")
    public R getCatelog(){
//        List<NginxResource> list = this.resourceList.stream()
//                .filter(item -> item.getRank() == rank)
//                .collect(Collectors.toList());
//        return R.ok().put("data",list);
        return R.ok().put("list",resourceList).put("parent","");
    }

    /**
     * 获取文件夹的子文件
     * @param simplePath:文件的简写路径
     * @return
     */
    @GetMapping("/getList")
    public R getList(@RequestParam String simplePath){
        System.out.println();
        if (StringUtils.isEmpty(simplePath)){
            return getCatelog();
        }
        File file = new File(pathPrefix+simplePath);
        if (!file.exists()) {
            return R.error(500,"文件夹不存在");
        }
        if (file.isFile()) {
            return R.error(500,"请传入文件夹");
        }

        File[] files = file.listFiles();
        List<NginxResource> list=new ArrayList<>(files.length);
        for (File f : files) {
            NginxResource res = new NginxResource();
            res.setName(f.getName());
            res.setSimplePath(simplePath+"/"+res.getName());
            res.setType(f.isDirectory()?"dir":res.getName().substring(res.getName().indexOf(".")+1));
            res.setUrl(urlPrefix+res.getSimplePath());
            res.setPath(f.getAbsolutePath());
            list.add(res);
        }
        return R.ok().put("list",list).put("parent",simplePath);
    }

    /**
     * 重命名
     * @param name：新的文件名
     * @param path：文件地址
     * @return
     */
    @PutMapping("/rename")
    public R rename(String name,String path){
        File file=new File(path);
        file.renameTo(new File(file.getParent() + "/" + name));
        return R.ok();
    }

    /**
     * 删除文件
     * @param path
     * @return
     */
    @DeleteMapping("/delete")
    public R delete(String path){
        if (!path.matches("^"+pathPrefix)){
            return R.error("无权限修改");
        }
        File file=new File(path);
        deleteBack(file);
        return R.ok();
    }

    private void deleteBack(File file){
        if(file.isFile()){
            file.delete();
            return;
        }
        File[] files = file.listFiles();
        for (File f : files) {
            deleteBack(f);
        }
        file.delete();
    }

    @Autowired
    HttpServletRequest request;
    /**
     * 上传文件或文件夹
     * @param files
     * @param parent 父文件的短文件名
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public R uploads(@RequestParam("files") MultipartFile[] files, @RequestParam("parent")String parent) throws IOException {
        if (parent==null||!parent.matches("^/.+")){
            return R.error(500,"不允许创建root目录");
        }
        for (MultipartFile file : files) {
            File file1 = new File(resourceConfig.getPathPrefix()+parent + "/" + file.getOriginalFilename());
            file1.mkdirs();
            file.transferTo(file1);
        }
        return R.ok("文件上传成功!");
    }
}
